package org.convallaria.framework.swagger.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.servers.Server;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * Swagger自动配置类
 * 
 * @author convallaria
 * @since 1.0.0
 */
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
@ConditionalOnProperty(prefix = "convallaria.swagger", name = "enabled", havingValue = "true", matchIfMissing = true)
@RequiredArgsConstructor
public class SwaggerAutoConfiguration {

    private final SwaggerProperties swaggerProperties;

    /**
     * 配置OpenAPI
     */
    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .info(createInfo())
                .servers(createServers());
    }

    /**
     * 创建API信息
     */
    private Info createInfo() {
        return new Info()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .version(swaggerProperties.getVersion())
                .contact(createContact())
                .license(createLicense());
    }

    /**
     * 创建联系信息
     */
    private Contact createContact() {
        SwaggerProperties.Contact contact = swaggerProperties.getContact();
        return new Contact()
                .name(contact.getName())
                .email(contact.getEmail())
                .url(contact.getUrl());
    }

    /**
     * 创建许可证信息
     */
    private License createLicense() {
        SwaggerProperties.License license = swaggerProperties.getLicense();
        return new License()
                .name(license.getName())
                .url(license.getUrl());
    }

    /**
     * 创建服务器列表
     */
    private List<Server> createServers() {
        return swaggerProperties.getServers().stream()
                .map(server -> new Server()
                        .url(server.getUrl())
                        .description(server.getDescription()))
                .toList();
    }
}
